<template>
  <div class="app-container">
    <div class="head-container">
      <el-input
        v-model="listQuery.condition"
        size="small"
        filterable
        placeholder="请输入表名称或描述"
        clearable
        style="width: 180px;"
      />

      <el-button
        type="success"
        icon="el-icon-search"
        size="mini"
        @click="getTablePage()"
      >
        查询
      </el-button>
      <el-button
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="openDialogTableForm(false)"
      >新增
      </el-button>
      <el-button-group>
        <el-button type="primary" size="mini" @click="createFile('all')">全部生成=》》</el-button>
        <el-button type="warning" size="mini" @click="createCode('model')">Model</el-button>
        <el-button type="warning" size="mini" @click="createCode('param')">Param</el-button>
        <el-button type="warning" size="mini" @click="createCode('vo')">Vo</el-button>
        <el-button type="warning" size="mini" @click="createCode('repository')">Repository</el-button>
        <el-button type="warning" size="mini" @click="createCode('mapper')">Mapper</el-button>
        <el-button type="warning" size="mini" @click="createCode('mapperXml')">MapperXml</el-button>
        <el-button type="warning" size="mini" @click="createCode('service')">Service</el-button>
        <el-button type="warning" size="mini" @click="createCode('serviceImpl')">ServiceImpl</el-button>
        <el-button type="warning" size="mini" @click="createCode('controller')">Controller</el-button>

        <el-button type="primary" size="mini" @click="createCode('sql')">Sql脚本</el-button>
      </el-button-group>
      <el-button-group>
        <el-button type="warning" size="mini" @click="createCode('vue_js')">Vue-js</el-button>
        <el-button type="warning" size="mini" @click="createCode('vue_index')">Vue-index</el-button>
      </el-button-group>
    </div>
    <div class="head-container">
      <el-table
        ref="genTable"
        v-loading="listLoading"
        :data="list"
        border
        fit
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column type="index" width="50" label="序号">
          <template slot-scope="scope">
            <span>{{listQuery.pageNo * listQuery.pageSize +scope.row.listIndex + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="tableName" label="数据表名" min-width="120"/>
        <el-table-column prop="tableNameDesc" label="数据表描述" min-width="100"/>
        <el-table-column prop="modelName" label="model名" min-width="100"/>
        <el-table-column prop="authorName" label="作者姓名" min-width="100"/>
        <el-table-column prop="javaPackage" label="Java包名" min-width="120"/>
        <el-table-column prop="vueApiPrefix" label="微服务名称" min-width="140"/>
        <el-table-column prop="jsPackage" label="Js包名" min-width="120"/>

        <el-table-column align="left" label="操作" min-width="200">
          <template slot-scope="scope">
            <el-button style="margin-left: 10px" type="primary" size="mini" @click="handleViewField(scope.row)">加载字段明细
            </el-button>
            <el-button style="margin-left: 10px" type="success" size="mini"
                       @click="openDialogTableForm(true,scope.row)">
              修改
            </el-button>
            <el-button style="margin-left: 10px" type="danger" size="mini" @click="handleDelete(scope.row)">删除
            </el-button>

          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        style="margin-top: 8px;"
        layout="total, prev, pager, next"
        :page-size="listQuery.pageSize"
        :total="total"
        prev-text="上一页"
        next-text="下一页"
        :current-page="listQuery.pageNo+1"
        @current-change="paginationChange"
      >
      </el-pagination>
      <!-- 弹出框新增table -->
      <el-dialog title="数据表信息" v-dialog-drag :visible.sync="dialogTableFormVisible">
        <el-form
          ref="tableForm"
          :model="tableForm"
          :rules="rules"
          label-position="right"
          label-width="120px"
          style="width: 600px; margin-left:20px; margin-right: 0px;"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据表名" prop="tableName">
                <el-input v-model="tableForm.tableName" maxlength="60"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="描述" prop="tableNameDesc">
                <el-input v-model="tableForm.tableNameDesc" maxlength="30"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="作者姓名" prop="authorName">
                <el-input v-model="tableForm.authorName" maxlength="60"/>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="model名" prop="modelName">
                <el-input v-model="tableForm.modelName" maxlength="60"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Java包名" prop="javaPackage">
                <el-input v-model="tableForm.javaPackage" maxlength="60"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="微服务名称" prop="vueApiPrefix">
                <el-input v-model="tableForm.vueApiPrefix" maxlength="60"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Js包名" prop="jsPackage">
                <el-input v-model="tableForm.jsPackage" maxlength="60"/>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button type="primary" plain @click="dialogTableFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveTable">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="代码生成" v-dialog-drag :visible.sync="dialogGenCodeVisible" width="900px">
        <el-form
          ref="genCodeForm"
          label-position="right"
          label-width="100px"
          style="width: 800px; margin-left:20px; margin-right: 20px;"
        >
          <el-input
            v-model="genCodeText"
            type="textarea"
            :rows="20"
          />
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button size="mini" @click="dialogGenCodeVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="copyCode">拷贝</el-button>
          <el-button size="mini" type="warning" @click="createFile('')">生成文件</el-button>
        </div>
      </el-dialog>
    </div>

    <el-dialog v-dialog-drag :visible.sync="row.show" title="字段详情" width="900px">
      <field :tableId = row.id :authorId="row.authorId"></field>
    </el-dialog>
  </div>
</template>

<script>
  import {addTable, editTable, deleteTable, getTablePage, createCode, createFile} from '@/api/system/codegen'
  import msgUtil from '@/utils/msgUtil'
  import field from '../field/index'

  // 定义table 的表单
  const tableForm = {
    id: '',
    tableName: '',
    tableNameDesc: '',
    modelName: '',
    authorName: '',
    javaPackage: '',
    vueApiPrefix: '',
    jsPackage: ''
  }

  export default {
    components: {
      field
    },
    data() {
      return {
        isEdit: false,
        tableForm: tableForm,
        dialogTableFormVisible: false, // 弹出的新增修改表单窗口
        dialogGenCodeVisible: false, // 弹出的生成代码窗口
        dialogGenSqlCodeVisible: false, // 弹出的生成代码窗口
        genCodeText: '', // 弹窗java代码
        genSqlCodeText: '', // 弹窗Sql的代码
        selTableId: 0, // 选中行的tableId
        selType: 0, // 选中的创建文件类型
        tableKey: 0,
        list: null,
        total: 0,
        listGenAhthorCombo: [],
        listLoading: false,
        listQuery: {
          condition: '',
          pageNo: 0,
          pageSize: 10
        },
        rules: {
          tableName: [{required: true, trigger: 'blur', message: '数据表名不能为空'}],
          tableNameDesc: [{required: true, trigger: 'blur', message: '数据表名描述不能为空'}],
          modelName: [{required: true, trigger: 'blur', message: 'model名不能为空'}],
          authorName: [{required: true, trigger: 'blur', message: '作者不能为空'}],
          javaPackage: [{required: true, trigger: 'blur', message: 'java包名不能为空'}],
          vueApiPrefix: [{required: true, trigger: 'blur', message: 'vueApiPrefix不能为空'}],
          jsPackage: [{required: true, trigger: 'blur', message: 'js包名不能为空'}],
        },
        row: {
          id: '',
          authorId: '',
          show: false
        }
      }
    },
    created() {
      this.getTablePage()
    },
    methods: {
      paginationChange(index) {
        this.listQuery.pageNo = index - 1
        this.getTablePage()
      },
      // 生成文件
      createFile(type) {
        // 判断是否选中行
        if (this.selTableId === 0) {
          this.$message({
            message: '请选择数据表',
            type: 'error'
          })
          return
        }
        if (type === 'all') {
          this.selType = type
        }
        const params = {tableId: this.selTableId, type: this.selType}
        createFile(params).then(response => {
          this.$message({
            message: '生成成功!文件位置: ' + response.data,
            type: 'success'
          })
        }).catch((response) => {
          this.$message({
            message: '代码文件生成失败',
            type: 'error'
          })
        })
      },
      // 拷贝代码
      copyCode() {
        this.$copyText(this.genCodeText).then(function (e) {
          msgUtil.success2('复制成功')
        }, function (e) {
          alert('Can not copy')
        })
      },
      handleSelectionChange(val) {
        if (val.length > 1) {
          this.$refs.genTable.clearSelection()
          this.$refs.genTable.toggleRowSelection(val[val.length - 1])
        } else if (val.length === 0) {
          this.selTableId = 0
        } else {
          this.multipleSelection = val[val.length - 1]
          this.selTableId = val[0].id
        }
      },
      // 删除
      handleDelete(row) {
        msgUtil.confirm('确认删除表数据?').then(async () => {
          const ids = []
          ids.push(row.id)
          await deleteTable(ids)
          msgUtil.success2('删除成功!')
          this.getTablePage()
        })
      },
      // 保存数据表配置
      saveTable() {
        this.$refs.tableForm.validate(valid => {
          if (valid) {
            if (this.isEdit) {
              editTable(this.tableForm).then(response => {
                this.dialogTableFormVisible = false
                this.$message({
                  message: '数据表修改成功',
                  type: 'success'
                })
                this.getTablePage()
              }).catch((response) => {
                this.$message({
                  message: '数据表修改失败',
                  type: 'error'
                })
              })
            } else {
              addTable(this.tableForm).then(response => {
                this.dialogTableFormVisible = false
                this.$message({
                  message: '数据表添加成功',
                  type: 'success'
                })
                this.getTablePage()
              }).catch((response) => {
                this.$message({
                  message: '数据表修改失败',
                  type: 'error'
                })
              })
            }
          }
        })
      },
      // 打开tableform窗口
      openDialogTableForm(isEdit, row) {
        this.isEdit = isEdit
        if (isEdit) {
          this.tableForm = row
          this.dialogTableFormVisible = true
        } else {
          this.dialogTableFormVisible = true
          this.tableForm = {
            id: '',
            tableName: '',
            tableNameDesc: '',
            modelName: '',
            authorName: '',
            javaPackage: '',
            vueApiPrefix: '',
            jsPackage: ''
          }
        }
      },
      createCode(type) {
        this.selType = type
        this.genCodeText = ''
        // 判断是否选中行
        if (this.selTableId === 0) {
          this.$message({
            message: '请选择数据表',
            type: 'error'
          })
          return
        }
        const params = {tableId: this.selTableId, type: type}
        createCode(params).then(res => {
          this.genCodeText = res.data
          this.dialogGenCodeVisible = true
        }).catch((response) => {
          this.$message({
            message: '代码生成失败',
            type: 'error'
          })
        })
      },
      getTablePage() {
        this.listLoading = true
        getTablePage(this.listQuery).then(res => {
          this.list = res.data.content
          this.total = res.data.totalElements
          res.data.content.forEach((item, index) => {
            item.listIndex = index
          });
          setTimeout(() => {
            this.listLoading = false
          }, 100)
        })
      },
      // 查看字段明细
      handleViewField(row) {
        this.row.tableId = row.id
        this.row.authorId = this.listQuery.authorId
        this.row.show = true
      }
    }
  }
</script>

